/**
 * 通用js方法封装处理
 * Copyright (c) 2019 ruoyi
 */


// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null;
  }
  const format = pattern || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string" && /^[0-9]+$/.test(time)) {
      time = parseInt(time);
    } else if (typeof time === "string") {
      time = time
        .replace(new RegExp(/-/gm), "/")
        .replace("T", " ")
        .replace(new RegExp(/\.[\d]{3}/gm), "");
    }
    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    if (result.length > 0 && value < 10) {
      value = "0" + value;
    }
    return value || 0;
  });
  return time_str;
}

/**
 *  计算周几
 * @param {日期} date
 * @returns
 */
export function getWeek(date) {
  let week = ""; //周几
  let weeks = {
    0: "星期日",
    1: "星期一",
    2: "星期二",
    3: "星期三",
    4: "星期四",
    5: "星期五",
    6: "星期六",
  };
  let weekIndex = date.getDay();
  week = weeks[weekIndex];
  return week;
}

/**
 * 计算百分比
 * @param {分子} numerator
 * @param {分母} denominator
 * @returns
 */
export function calculatePercentage(numerator, denominator) {
  if (denominator === 0 || isNaN(numerator) || isNaN(denominator)) {
    return "0.00%"; // 防止除以0或非数字
  }
  const percentage = ((numerator / denominator) * 100).toFixed(2); // 保留两位小数
  return `${percentage}%`; // 返回格式化的百分比字符串
}

/**
 * 计算时差
 * @param {} time
 */
export function timeDifference(time) {
  const now = new Date();
  const target = new Date(time);
  const difference = target - now; // 时间差，单位毫秒

  // 将时间差转换为更可读的格式
  let days = Math.floor(difference / (1000 * 60 * 60 * 24));
  let hours = Math.floor(
    (difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
  );
  let minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
  let seconds = Math.floor((difference % (1000 * 60)) / 1000);

  return `${days} 天`;
}

/**
 * 计算时差
 * @param {开始时间} beginTime
 * @param {结束时间} endTime
 * @returns
 */
export function timeDifferenceDetails(beginTime, endTime) {
  var dateDiff = endTime.getTime() - beginTime.getTime(); //时间差的毫秒数
  var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000)); //计算出相差天数
  var leave1 = dateDiff % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
  var hours = Math.floor(leave1 / (3600 * 1000)); //计算出小时数
  //计算相差分钟数
  var leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
  var minutes = Math.floor(leave2 / (60 * 1000)); //计算相差分钟数
  //计算相差秒数
  var leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
  var seconds = Math.round(leave3 / 1000);
  return {
    dayDiff: dayDiff,
    hours: hours,
    minutes: minutes,
  };
}

/*
 * 参数说明：
 * number：要格式化的数字
 * decimals：保留几位小数
 * dec_point：小数点符号
 * thousands_sep：千分位符号
 * */
export function toMoney(number, decimals = 2, dec_point, thousands_sep) {
  number = (number + "").replace(/[^0-9+-Ee.]/g, "");
  var n = !isFinite(+number) ? 0 : +number,
    prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
    sep = typeof thousands_sep === "undefined" ? "," : thousands_sep,
    dec = typeof dec_point === "undefined" ? "." : dec_point,
    s = "",
    toFixedFix = function (n, prec) {
      var k = Math.pow(10, prec);
      return "" + Math.ceil(n * k) / k;
    };
  s = (prec ? n.toFixed(prec) : "" + Math.round(n)).split(".");
  var re = /(-?\d+)(\d{3})/;
  // toFixedFix(n, prec)
  // n.toFixed(prec)
  while (re.test(s[0])) {
    s[0] = s[0].replace(re, "$1" + sep + "$2");
  }
  if ((s[1] || "").length < prec) {
    s[1] = s[1] || "";
    s[1] += new Array(prec - s[1].length + 1).join("0");
  }
  return "￥" + s.join(dec);
}

/*
 * 参数说明：格式化数字,增加千分号,去掉小数尾数0
 * number：要格式化的数字
 * */
export function formattedNumber(number){
    if(null != number){
      let numStr = Number(number.toFixed(4));
      let formatter = new Intl.NumberFormat('en-US', {
        style: 'decimal',
        minimumFractionDigits: 4, // 最小小数位数
        maximumFractionDigits: 4  // 最大小数位数
      });
      return "￥" + formatter.format(numStr).toString().replace(/\.?0+$/, '');
    }else{
      return "￥0";
    }
}

/**
 * 数字转大写
 * @param {*} money
 * @returns
 */
export function toUpperCaseAmount(money){
  // 汉字的数字
	var cnNums = new Array('零', '壹', '贰', '叁', '肆', '伍', '陆',
  '柒', '捌', '玖');
// 基本单位
var cnIntRadice = new Array('', '拾', '佰', '仟');
// 对应整数部分扩展单位
var cnIntUnits = new Array('', '万', '亿', '兆');
// 对应小数部分单位
var cnDecUnits = new Array('角', '分', '毫', '厘');
// 整数金额时后面跟的字符
var cnInteger = '整';
// 整型完以后的单位
var cnIntLast = '元';
// 最大处理的数字
var maxNum = 999999999999999.9999;
// 金额整数部分
var integerNum;
// 金额小数部分
var decimalNum;
// 输出的中文金额字符串
var chineseStr = '';
// 分离金额后用的数组，预定义
var parts;
if (money == '') {
  return '';
}
money = parseFloat(money);
if (money >= maxNum) {
  // 超出最大处理数字
  return '';
}
if (money == 0) {
  chineseStr = cnNums[0] + cnIntLast + cnInteger;
  return chineseStr;
}
// 转换为字符串
money = money.toString();
if (money.indexOf('.') == -1) {
  integerNum = money;
  decimalNum = '';
} else {
  parts = money.split('.');
  integerNum = parts[0];
  decimalNum = parts[1].substr(0, 4);
}
// 获取整型部分转换
if (parseInt(integerNum, 10) > 0) {
  var zeroCount = 0;
  var IntLen = integerNum.length;
  for (var i = 0; i < IntLen; i++) {
      var n = integerNum.substr(i, 1);
      var p = IntLen - i - 1;
      var q = p / 4;
      var m = p % 4;
      if (n == '0') {
          zeroCount++;
      } else {
          if (zeroCount > 0) {
              chineseStr += cnNums[0];
          }
          // 归零
          zeroCount = 0;
          chineseStr += cnNums[parseInt(n)]
              + cnIntRadice[m];
      }
      if (m == 0 && zeroCount < 4) {
          chineseStr += cnIntUnits[q];
      }
  }
  chineseStr += cnIntLast;
}
// 小数部分
if (decimalNum != '') {
  var decLen = decimalNum.length;
  for (var i = 0; i < decLen; i++) {
      var n = decimalNum.substr(i, 1);
      if (n != '0') {
          chineseStr += cnNums[Number(n)] + cnDecUnits[i];
      }
  }
}
if (chineseStr == '') {
  chineseStr += cnNums[0] + cnIntLast + cnInteger;
} else if (decimalNum == '') {
  chineseStr += cnInteger;
}
return chineseStr;
}

// 表单重置
export function resetForm(refName) {
  if (this.$refs[refName]) {
    this.$refs[refName].resetFields();
  }
}


// 添加日期范围
export function addDateRange(params, dateRange, propName) {
  let search = params;
  search.params =
    typeof search.params === "object" &&
    search.params !== null &&
    !Array.isArray(search.params)
      ? search.params
      : {};
  dateRange = Array.isArray(dateRange) ? dateRange : [];
  if (typeof propName === "undefined") {
    search.params["beginTime"] = dateRange[0];
    search.params["endTime"] = dateRange[1];
  } else {
    search.params["begin" + propName] = dateRange[0];
    search.params["end" + propName] = dateRange[1];
  }
  return search;
}

// 回显数据字典
export function selectDictLabel(datas, value) {
  if (value === undefined) {
    return "";
  }
  var actions = [];
  Object.keys(datas).some((key) => {
    if (datas[key].value == "" + value) {
      actions.push(datas[key].label);
      return true;
    }
  });
  if (actions.length === 0) {
    actions.push(value);
  }
  return actions.join("");
}

// 回显数据字典（字符串、数组）
export function selectDictLabels(datas, value, separator) {
  if (value === undefined || value.length === 0) {
    return "";
  }
  if (Array.isArray(value)) {
    value = value.join(",");
  }
  var actions = [];
  var currentSeparator = undefined === separator ? "," : separator;
  var temp = value.split(currentSeparator);
  Object.keys(value.split(currentSeparator)).some((val) => {
    var match = false;
    Object.keys(datas).some((key) => {
      if (datas[key].value == "" + temp[val]) {
        actions.push(datas[key].label + currentSeparator);
        match = true;
      }
    });
    if (!match) {
      actions.push(temp[val] + currentSeparator);
    }
  });
  return actions.join("").substring(0, actions.join("").length - 1);
}

// 字符串格式化(%s )
export function sprintf(str) {
  var args = arguments,
    flag = true,
    i = 1;
  str = str.replace(/%s/g, function () {
    var arg = args[i++];
    if (typeof arg === "undefined") {
      flag = false;
      return "";
    }
    return arg;
  });
  return flag ? str : "";
}

// 转换字符串，undefined,null等转化为""
export function parseStrEmpty(str) {
  if (!str || str == "undefined" || str == "null") {
    return "";
  }
  return str;
}

// 数据合并
export function mergeRecursive(source, target) {
  for (var p in target) {
    try {
      if (target[p].constructor == Object) {
        source[p] = mergeRecursive(source[p], target[p]);
      } else {
        source[p] = target[p];
      }
    } catch (e) {
      source[p] = target[p];
    }
  }
  return source;
}

// 生成单号
export function generatePolicyNumber(name) {
  const timestamp = new Date().getTime().toString();
  const randomNumber = Math.floor(1000 + Math.random() * 9000).toString();
  return `${name}${timestamp}${randomNumber}`;
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data, id, parentId, children) {
  let config = {
    id: id || "id",
    parentId: parentId || "parentId",
    childrenList: children || "children",
  };

  var childrenListMap = {};
  var nodeIds = {};
  var tree = [];

  for (let d of data) {
    let parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  }

  for (let d of data) {
    let parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  }

  for (let t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      for (let c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }
  return tree;
}

/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params) {
  let result = "";
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    var part = encodeURIComponent(propName) + "=";
    if (value !== null && value !== "" && typeof value !== "undefined") {
      if (typeof value === "object") {
        for (const key of Object.keys(value)) {
          if (
            value[key] !== null &&
            value[key] !== "" &&
            typeof value[key] !== "undefined"
          ) {
            let params = propName + "[" + key + "]";
            var subPart = encodeURIComponent(params) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result;
}

// 验证是否为blob格式
export function blobValidate(data) {
  return data.type !== "application/json";
}

// 根据身份证计算年龄
export function calculateAge(idcard) {
  if (!idcard) return 0;
  // 提取出生日期
  const birthYear = parseInt(idcard.slice(6, 10));
  const birthMonth = parseInt(idcard.slice(10, 12));
  const birthDay = parseInt(idcard.slice(12, 14));

  // 创建日期对象
  const birthDate = new Date(birthYear, birthMonth - 1, birthDay);

  // 计算年龄
  const currentYear = new Date().getFullYear();
  const currentMonth = new Date().getMonth() + 1;
  const currentDay = new Date().getDate();

  let age = currentYear - birthYear;

  if (
    currentMonth < birthMonth ||
    (currentMonth === birthMonth && currentDay < birthDay)
  ) {
    age--;
  }

  return age <= 0 ? "" : age;
}
